#define _CRT_SECURE_NO_WARNINGS 1
#include "SList.h"


SLNode* BuySListNode(SLTDataType x)
{
	SLNode* P = (SLNode*)malloc(sizeof(SLNode));
	if (P == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}
	P->Data = x;
	P->Next = NULL;

	return P;
}


SLNode* CreadList(int n)
{
	int i = 0;
	SLNode* head = NULL; SLNode*  tail = NULL;
	for (i = 0; i < n; i++)
	{
		SLNode* New = BuySListNode(i);

		if (head == NULL)
		{
			head = tail = New;
		}
		else
		{
			tail->Next = New;
			tail = New;
		}
	}
	return head;
}


void SlistPrint(SLNode* Phead)
{

	while (Phead)
	{
		printf("%d->", Phead->Data);
		Phead = Phead->Next;
	}
	printf("NULL\n");
}

void SlistPushBack(SLNode** PPhead, SLTDataType x)
{
	SLNode* New = BuySListNode(x);
	if ( *PPhead == NULL)
	{
		*PPhead = New;
	}
	else
	{
		SLNode* tail = *PPhead;
		while (tail->Next != NULL)
		{
			
			tail = tail->Next;
		}
		
		tail->Next = New;
		
	}
	
}

void SlistPopBack(SLNode** PPhead)
{
	assert(PPhead);
	SLNode* TP = *PPhead;
	if (TP->Next == NULL)
	{
		free(TP);
	}
	else
	{
		while (TP->Next->Next)
			{
				TP = TP->Next;
			}
		free(TP->Next->Next);
			TP->Next = NULL;
	}
}

void SListPushfront(SLNode** PPhead, SLTDataType x)
{
	SLNode* New = BuySListNode(x);
	New->Next = *PPhead;
	*PPhead = New;
}

void SListPopfront(SLNode** PPhead)
{
	assert(*PPhead);
	*PPhead = (*PPhead)->Next;
}

SLNode* SLFind(SLNode* Phead, SLTDataType x)
{
	SLNode* TP = Phead ;

	while ( TP )
	{
		if (TP->Data == x)
		{
			return TP;
		}
		TP = TP->Next;

	}
	return NULL;
}

void SLInsertAfter(SLNode** PPhead, SLTDataType x)
{
	SLNode* TP = *PPhead;
	SLNode* TP_next = TP->Next;
	SLNode* New = BuySListNode(x);
	TP->Next = New;
	New->Next = TP_next;
}


void SLInsertFrom(SLNode** PPhead, SLNode* Phead, SLTDataType x)
{
	assert(Phead);
	SLNode* TP = *PPhead;
	
	SLNode* New = BuySListNode(x);
	if (TP == Phead)
	{
		SListPushfront(PPhead, x);
	}
	else
	{
		while (TP != NULL)
		{
			if (TP->Next != Phead)
			{
				TP = TP->Next;
			}
		
				TP->Next= New;
		 
			New->Next = Phead;
		
		}
	}
	
}


void SLEraseAfter(SLNode* Phead)
{
	SLNode* TP = Phead;
	SLNode* TP_next = TP->Next;
	if (TP->Next == NULL)
	{

	}
	else
	{
		if (TP->Next->Next == NULL)
		{
			TP->Next = NULL;
			free(TP_next);
		}
		else
		{
			TP->Next = TP->Next->Next;
			free(TP_next);
		}
	}
}


void SListDestroy(SLNode** PPhead)
{
	SLNode* TP = *PPhead;
	while (TP)
	{
		SLNode* ne = TP->Next;
		free(TP);
		TP = ne;
	}
}
